package com.delayqueue.common.task;

import com.delayqueue.common.enums.ExecutorType;
import com.delayqueue.common.enums.TaskStatus;

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;


public class Task implements Delayed {

    private long executeTime;
    private TaskStatus status = TaskStatus.NORMAL;
    private String code;
    private ExecutorType executorType;
    private boolean async = false;  //是否异步执行
    private boolean cycle = false; //是否循环执行

    public Task() {
    }

    public Task(String code) {
        this.code = code;
    }

    public Task(String code, ExecutorType executorType, long executeTime) {
        this.code = code;
        this.executorType = executorType;
        this.executeTime = executeTime;
    }

    public Task(ExecutorType executorType, long executeTime) {
        this.executorType = executorType;
        this.executeTime = executeTime;
    }

    public boolean canExecute() {
        return status == TaskStatus.NORMAL;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Task task = (Task) o;
        if (code == null) {
            return false;
        }
        return code.equals(task.code);
    }

    @Override
    public int hashCode() {
        return Objects.hash(code);
    }

    @Override
    public int compareTo(Delayed o) {
        return executeTime >= ((Task) o).getExecuteTime() ? 1 : -1;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return executeTime - System.currentTimeMillis();
    }

    public long getExecuteTime() {
        return executeTime;
    }

    public void setExecuteTime(long executeTime) {
        this.executeTime = executeTime;
    }

    public TaskStatus getStatus() {
        return status;
    }

    public void setStatus(TaskStatus status) {
        this.status = status;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public ExecutorType getExecutorType() {
        return executorType;
    }

    public void setExecutorType(ExecutorType executorType) {
        this.executorType = executorType;
    }

    public boolean isAsync() {
        return async;
    }

    public void setAsync(boolean async) {
        this.async = async;
    }

    public boolean isCycle() {
        return cycle;
    }

    public void setCycle(boolean cycle) {
        this.cycle = cycle;
    }
}
